import router from "@src/router";
import { getAppointmentShopDetail, getGoodsList } from "@src/api/reservation";
import reservation from "@src/store/reservation";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import {
  SHARE_PATH,
  OPEN_STATE,
  OPEN_STATE_TEXT,
  OPEN_STATE_CLEW_TEXT,
} from "@src/common/reservation/constant/index.js";
import location from "@src/store/location";
import base from "@src/store/base";

Page({
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: reservation,
      fields: ["goodsInfo"],
      actions: ["setSubmitGoodsInfo"],
    },
    {
      store: location,
      fields: ["latitude", "longitude"],
      actions: ["getLocation", "showAuthTip"],
    },
    {
      store: base,
      fields: ["isiPhoneX", "themeColor", "themeTitleColor"],
    },
  ],
  data: {
    sysWidth: wx.getSystemInfoSync().windowWidth - 50, //屏幕宽度 ---悬浮窗位置
    sysHeight: wx.getSystemInfoSync().windowHeight / 2 + 60, //屏幕高度
    loading: false,
    //店铺信息
    shopInfo: {},
    indicatorIndex: 1,
    OPEN_STATE,
    OPEN_STATE_TEXT,
    OPEN_STATE_CLEW_TEXT,
    //商品选择器
    //商品选择器
    isShowGoodSelect: false,
    //时间选择器
    isShowTimeSelect: false,
    //分享弹出层
    isShowShareLink: false,
    //参数弹出层
    isShowParameterModal: false,
    //信息
    options: {},
    categoryList: {},
    planInfo: {},
    //商品信息
    goodsData: {},
    skuId: null,
    minPrice: 0,
    categoryId: null,
    categoryTitle: null,
    planId: null,
    specTitle: null,
    voucher: ["平台担保", "商家认证", "到店付"],
    //时间信息
    dateTimeInfo: {},
    //分享商品
    isShowShareGood: false,
    shareDetail: {},
    parameterList: [],
    parameterTitle: "参数",
    disabledChoose: false,
    notSelectable: true,
  },
  //下拉刷新
  onPullDownRefresh() {
    wx.showLoading({ title: "加载中" });
    this.setData({ loading: true });
    this.fetchData();
  },
  onShareAppMessage: function () {
    let fileBaseUrl = getApp().globalData.extConfig.fileBaseUrl;
    const {
      shopInfo: {
        shopInfoResp: { shopId, shopConfigId },
      },
      planInfo,
      goodsData,
    } = this.data;
    return {
      title: goodsData.goods.title,
      imageUrl: fileBaseUrl + goodsData.goods.imgList[0],
      path: `/sp-reservation/pages/project_detail/main?planId=${planInfo.planId}&shopId=${shopId}&shopConfigId=${shopConfigId}&goodsSerial=${goodsData.goodsSerial}`,
    };
    // return custom share data when user share.
  },
  onShareTimeline: function () {
    let fileBaseUrl = getApp().globalData.extConfig.fileBaseUrl;
    const {
      shopInfo: {
        shopInfoResp: { shopId, shopConfigId },
      },
      planInfo,
      goodsData,
    } = this.data;
    return {
      title: goodsData.goods.title,
      imageUrl: fileBaseUrl + goodsData.goods.imgList[0],
      path: `/sp-reservation/pages/project_detail/main?planId=${planInfo.planId}&shopId=${shopId}&shopConfigId=${shopConfigId}&goodsSerial=${goodsData.goodsSerial}`,
    };
    // return custom share data when user share.
  },
  onShow() {
    // 接收从门店列表页（store-list）返回当前页的数据
    const pages = getCurrentPages();
    const currPage = pages[pages.length - 1];
    // console.log('预约---接收门店列表的数据 currPage', currPage.data.storeData)
    if (currPage.data.storeData) {
      let shopId = currPage.data.storeData.shopId;
      let shopConfigId = currPage.data.storeData.shopConfigId;
      this.data.options.shopId = shopId;
      this.data.options.shopConfigId = shopConfigId;
      this.setData({ options: this.data.options });
      this.fetchData();
    }
  },
  onLoad: function (options) {
    wx.showLoading({ title: "加载中" });
    this.setData({
      options,
    });
    console.log(">>>onLoad", options);
    // this.fetchData();
  },
  onLogin() {
    this.getLocation(true)
      .then((res) => {
        if (this.data.options.shopId) {
          this.setData({ latitude: res.latitude, longitude: res.longitude });
          this.fetchData(true);
        }
      })
      .catch((res) => {
        if (this.data.options.shopId) {
          this.fetchData(true);
        }
      });
  },
  callPhone(e) {
    console.log("e", e);
    let mobilePhone = e.currentTarget.dataset.phone;
    if (mobilePhone) {
      wx.makePhoneCall({
        phoneNumber: mobilePhone,
      });
    }
  },
  async fetchData() {
    const { goodsSerial, shopId, shopConfigId, planId } = this.data.options;
    const { latitude = "", longitude = "" } = this.data;
    const { code, data } = await getGoodsList({
      goodsSerial,
      shopConfigId: shopConfigId,
      planId,
      shopId,
    });
    if (code === 0) {
      const { categoryList, goodsPageData, planInfo, minPrice } = data;
      this.setData({
        categoryList,
        goodsData: goodsPageData,
        planInfo,
        minPrice,
      });
    }
    const { code: code1, data: data1 } = await getAppointmentShopDetail({
      shopId,
      latitude: latitude || "",
      longitude: longitude || "",
    });
    if (code1 === 0) {
      wx.hideLoading();
      wx.stopPullDownRefresh();
      this.setData({ loading: false });
      // data1.shopLabel = data1.shopLabel.split(",");
      const shopLabel = data1.shopLabel.split(",");
      const labels = [];
      shopLabel.forEach((v) => {
        if (v.trim()) {
          labels.push(v);
        }
      });
      // data1.shopLabel = shopLabel.slice(0, shopLabel.length - 1);
      data1.shopLabel = labels;
      data1.distance = (data1.shopInfoResp.distance / 1000).toFixed(2);
      // console.log("shopLabel", data1.shopLabel);
      this.setData({
        shopInfo: data1,
        disabledChoose:
          data1.shopInfoResp.allStatus !== OPEN_STATE.ON &&
          data1.shopInfoResp.allStatus !== OPEN_STATE.REST
            ? true
            : !this.data.planInfo.available,
      });
    }
    //初始化操作
    const skuInfo = this.data.goodsData.skuInfo.skuList.filter(
      (v) => v.status === 1
    )[0];
    const notSelectable =
      this.data.goodsData.skuInfo.skuList.filter((v) => v.status === 0)
        .length === this.data.goodsData.skuInfo.skuList.length;
    const specInfo = this.data.goodsData.skuInfo.specList[0];
    const { skuList, specList } = this.data.goodsData.skuInfo;
    let specTitle = [];
    skuInfo?.specAttrs.forEach((v) => {
      specList.forEach((spi, spIndex) => {
        spi.attrList.forEach((attri) => {
          if (v === attri.id) {
            console.log(v, attri);
            specTitle[spIndex] = attri.title;
            this.setData({
              specTitle: specTitle.join(","),
            });
          }
        });
      });
    });
    console.log("初始化操作", this.data.goodsData, notSelectable);
    this.setData({
      skuId: skuInfo?.skuId || 0,
      notSelectable: notSelectable,
      categoryId:
        this.data.categoryList.length > 0 ? this.data.categoryList[0].id : "",
      planId: this.data.planInfo.planId || 0,
      // specTitle: `${specInfo?.attrList[0].title || ""}`,
      categoryTitle:
        this.data.categoryList.length > 0
          ? this.data.categoryList[0].levelName
          : "",
    });
  },
  //跳转到新的门店列表
  handleToNewShopList() {
    router.push({
      name: "mall/store-list",
      params: { shopId: this.data.shopId, storeType: "reservation" },
    });
  },
  handleImageChange(e) {
    let indicatorIndex = e.detail.current + 1;
    this.setData({ indicatorIndex: indicatorIndex });
  },
  //商品选择器
  handleShowSelectGood() {
    if (this.data.shopInfo.shopInfoResp.allStatus !== OPEN_STATE.ON) return;
    this.setData({
      isShowGoodSelect: !this.data.isShowGoodSelect,
    });
  },
  handleCloseSelectGood() {
    this.setData({
      isShowGoodSelect: false,
    });
  },
  handleSelectGoods(e) {
    console.log("handleSelectGoods", e);
    const {
      detail: { skuId, specTitle },
    } = e;
    if (skuId > 0) {
      this.setData({
        skuId,
        specTitle,
      });
    }
    if (this.data.skuId === null || this.data.skuId === undefined) {
      wx.showModal({
        content: "请选择方案",
        showCancel: false,
      });
      return;
    }
    this.setData({
      isShowGoodSelect: false,
    });
    this.setData({
      isShowTimeSelect: true,
    });
  },
  handleSelectCategory(e) {
    const {
      detail: { planId, id },
    } = e;
    this.setData({
      categoryId: id,
      planId,
      categoryTitle: this.data.categoryList.filter((v) => v.id === id)[0]
        .levelName,
    });
    console.log("handleSelectCategory", this.data.categoryId);
  },
  //时间选择器
  handleShowSelectTime() {
    if (this.data.disabledChoose) {
      return;
    }
    //如果是无等级和无规格的时候，直接弹出选择时间
    if (
      !this.data.categoryTitle &&
      this.data.goodsData.skuInfo.specList.length === 0
    ) {
      this.setData({
        isShowTimeSelect: true,
        // isShowTimeSelect: !this.data.isShowTimeSelect,
      });
      return;
    }
    this.setData({
      isShowGoodSelect: true,
      // isShowTimeSelect: !this.data.isShowTimeSelect,
    });
  },
  handleCloseSelectTime() {
    this.setData({
      isShowTimeSelect: false,
    });
  },
  handleSelectDateTime(e) {
    const { detail } = e;
    this.setData({
      dateTimeInfo: detail,
    });
    console.log("选择了时间", e);
  },
  handleConfirmSelect() {
    console.log("handleConfirmSelect1");
    // 预约时间，套餐信息，sku信息
    const {
      categoryList,
      goodsData: {
        skuInfo: { skuList, specList },
      },
      skuId,
      planId,
      categoryId,
      dateTimeInfo,
    } = JSON.parse(JSON.stringify(this.data));
    //资源信息
    const categoryInfo =
      categoryList.filter(
        (v) => v.id === categoryId && v.planId === planId
      )[0] || {};
    categoryInfo.serviceDuration = this.data.planInfo.serviceDuration;
    categoryInfo.planId = this.data.planInfo.planId;
    //sku信息
    const skuInfo = skuList.filter((v) => v.skuId === skuId)[0];
    //spec套餐信息
    const specAttrs = skuInfo?.specAttrs;
    let specs = [];
    specList.forEach((spItem) => {
      if (spItem.attrList.length > 0) {
        spItem.attrList.forEach((v) => {
          if (specAttrs.includes(v.id)) {
            specs.push(v);
          }
        });
      }
    });
    //预约时间
    const goodsInfo = {
      categoryInfo,
      skuInfo,
      specs,
      dateTimeInfo,
    };
    goodsInfo.skuInfo = {
      ...this.data.goodsData.goods,
      ...goodsInfo.skuInfo,
      id: this.data.goodsData.goodsId,
      shopConfigId: this.data.options.shopConfigId,
      imgUrl: goodsInfo?.skuInfo.imgUrl || this.data.goodsData.goods.imgList[0],
    };
    if (
      dateTimeInfo.time === null ||
      dateTimeInfo.time === undefined ||
      dateTimeInfo.time.num === null ||
      dateTimeInfo.time.num === undefined ||
      dateTimeInfo.time.num <= 0 ||
      skuInfo.skuId === null ||
      skuInfo.skuId === undefined ||
      skuInfo.price === null ||
      skuInfo.price === undefined
    )
      return;
    this.setSubmitGoodsInfo(JSON.stringify(goodsInfo)).then(() => {
      wx.showLoading({
        title: "保存信息中",
      });
      setTimeout(() => {
        wx.hideLoading();
        const categoryIds = encodeURIComponent(dateTimeInfo.time.categoryIds);
        const date = encodeURIComponent(
          `${this.data.dateTimeInfo.date.value} ${this.data.dateTimeInfo.time.time}`
        );
        console.log("保存信息中", goodsInfo, categoryIds);
        // router.push({
        //   name: "reservation/choose_resources",
        //   params: {
        //     categoryIds,
        //     planId: categoryInfo.planId,
        //     shopId: this.data.shopInfo.shopInfoResp.shopId,
        //     date,
        //     // navIndex: e.currentTarget.dataset.index,
        //   },
        // });
        if (categoryInfo.id !== null && categoryInfo.id !== undefined) {
          router.push({
            name: "reservation/choose_resources",
            params: {
              categoryIds,
              planId: categoryInfo.planId,
              shopId: this.data.shopInfo.shopInfoResp.shopId,
              date,
              // navIndex: e.currentTarget.dataset.index,
            },
          });
        } else {
          router.push({
            name: "reservation/submit_reservation",
            params: {
              title: 0,
              shopId: this.data.shopInfo.shopInfoResp.shopId,
              // navIndex: e.currentTarget.dataset.index,
            },
          });
        }
      }, 500);
    });
  },
  //分享弹出层
  handleShowShareLink() {
    console.log("isShowShareLink");
    this.setData({
      isShowShareLink: !this.data.isShowShareLink,
    });
  },
  handleToShop() {
    router.push({
      name: "reservation/home",
    });
  },
  //跳转到新的门店列表
  handleToNewShopList() {
    router.push({
      name: "mall/store-list",
      params: { shopId: this.data.shopId, storeType: "reservation" },
    });
  },
  onShowShareGood() {
    const { planInfo } = this.data;

    const { goodsSerial, shopId, shopConfigId, id } = this.data.options;
    const shareDetail = {
      goodsVOList: [
        {
          goodsSerial,
        },
      ],
      appointmentPlanId: planInfo.planId,
      planId: planInfo.planId,
      path: SHARE_PATH,
      shopConfigId,
      shopId,
    };
    this.setData({
      shareDetail,
      isShowShareGood: true,
    });
  },
  handleCloseShare() {
    this.setData({
      isShowShareGood: false,
    });
  },
  handleShowVouchersParameterModal() {
    const {
      goods: { serviceList },
    } = this.data.goodsData;
    const list = serviceList.map((v) => {
      v.name = v.title;
      v.value = v.description;
      return v;
    });
    this.setData({
      parameterTitle: "服务",
      parameterList: list,
      isShowParameterModal: !this.data.isShowParameterModal,
    });
  },
  handleShowParameterModal() {
    this.setData({
      parameterTitle: "项目参数",
      parameterList: this.data.goodsData.goods.goodsParams,
      isShowParameterModal: !this.data.isShowParameterModal,
    });
  },
  handleToShopList() {
    router.push({
      name: "mall/store-list",
      params: { shopId: this.data.shopId, storeType: "reservation" },
    });
  },
});
